package oa.hleast.xswl.service.chat.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.utils.JsonUtil;
import oa.hleast.xswl.common.config.WebSocketConfig;
import oa.hleast.xswl.common.constant.ChatterTypeEnum;
import oa.hleast.xswl.controller.ws.IWebSocket;
import oa.hleast.xswl.pojo.domain.chat.CmsChatMessageLog;
import oa.hleast.xswl.pojo.domain.chat.CmsChatSession;
import oa.hleast.xswl.service.chat.CmsChatSessionService;
import oa.hleast.xswl.service.chat.IChatMessageLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.Session;
import java.io.IOException;
import java.util.List;

/**
 * @author 00204
 */
@Service
@Slf4j
@Transactional
@AllArgsConstructor
public class WebSocketServerService implements IWebSocket {

    private IChatMessageLogService iChatMessageLogService;
    private CmsChatSessionService cmsChatSessionService;

    @Override
    public void onOpen(String userId, Session session) {
        log.info("现在来连接的服务端用户id：" + userId);
        //把自己的信息加入到map当中去
        WebSocketConfig.server.put(userId, session);
        //查询所有客服发送未读消息
        List<CmsChatMessageLog> listMsg = iChatMessageLogService.list(new LambdaQueryWrapper<CmsChatMessageLog>()
                .eq(CmsChatMessageLog::getSendStatus, 1)
                .eq(CmsChatMessageLog::getChatterType, "USER")
                .eq(CmsChatMessageLog::getChatId, Long.parseLong(userId)));
        if (listMsg.size() > 0) {
            session.getAsyncRemote().sendText(JsonUtil.obj2String(listMsg));
        }
        //修改消息发送状态
        LambdaUpdateWrapper<CmsChatMessageLog> updateWrapper = new LambdaUpdateWrapper<CmsChatMessageLog>().eq(CmsChatMessageLog::getChatId, Long.parseLong(userId));
        updateWrapper.set(CmsChatMessageLog::getSendStatus, CmsChatMessageLog.SEND_STATUS_SUCCESS);
        iChatMessageLogService.update(updateWrapper);
    }

    @Override
    public void handleMessage(String userId, String message, Session session,String messageType,String assetUrl) throws IOException {
        log.info("服务端发送消息：" + message + "客户端的id是：" + userId);
        if (WebSocketConfig.clients.containsKey(userId)) {
            //将消息存储至数据库
            CmsChatMessageLog msg = CmsChatMessageLog.builder()
                    .chatId(Long.parseLong(userId))
                    .chatterId(Long.parseLong(userId))
                    .chatterType(ChatterTypeEnum.SYS.name())
                    .content(message)
                    .type(messageType)
                    .sendStatus(CmsChatMessageLog.SEND_STATUS_SUCCESS)
                    .build();
            iChatMessageLogService.save(msg);
            sendMessageTo(JsonUtil.obj2String(msg), userId);

        } else {
            //将消息存储至数据库
            iChatMessageLogService.save(CmsChatMessageLog.builder()
                    .chatId(Long.parseLong(userId))
                    .chatterId(Long.parseLong(userId))
                    .chatterType(ChatterTypeEnum.SYS.name())
                    .content(message)
                    .type(messageType)
                    .sendStatus(CmsChatMessageLog.SEND_STATUS_FAIL)
                    .build());
        }
        //修改回复状态
        LambdaUpdateWrapper<CmsChatSession> updateWrapper = new LambdaUpdateWrapper<CmsChatSession>().eq(CmsChatSession::getId, Long.parseLong(userId));
        updateWrapper.set(CmsChatSession::getReplyStatus, CmsChatSession.REPLY_STATUS_ARTI);
        cmsChatSessionService.update(updateWrapper);

    }


    public void sendMessageTo(String message, String userId) throws IOException {
        WebSocketConfig.clients.get(userId).getBasicRemote().sendText(message);
    }

    public void sendMessageAll(String message) throws IOException {
        for (Session item : WebSocketConfig.clients.values()) {
            item.getAsyncRemote().sendText(message);
        }
    }
}
